var Take6Model = require("Take6Model");
var TestPlayerIndex = 0;

cc.Class({
    extends: cc.Component,

    properties: {
            randomCard: {
                default: null,
                type: cc.Prefab
            },
            playerBoard: {
                default: null,
                type: cc.Prefab
            },
            tipArrow : {
                default: null,
                type: cc.Prefab
            },
            cardToPunch : {
                default: null,
                type: cc.Prefab
            },
            punchSpark : {
                default: null,
                type: cc.Prefab
            },
            resultBoard : {
                default: null,
                type: cc.Prefab
            },
            maskLayer: {
                default: null,
                type: cc.Prefab
            },
            punchFrame : cc.SpriteFrame,

            readyCardOffsetX : 200.0,
            readyCardPositionY : -120,
            readyCardScale : 0.8,
            flPulicCardPositionY : 210,
            flPlayerCardStartY : -440,

            flGotoGroupDuring : 1.0,

            cardGroups : [],
            cardGroupHeadNum : [],
            cardPositionsX : [],
            readyCardPositionX : [],
            rgPlayerCards : [],
            rgReadyCards : [],
            rgTipArrows : [],
            rgPlayerBoards : [],

            ws : {
                default : null,
                visible : false
            },

            nCurrentReadyPositionIndex : {
                default : 0,
                visible : false
            },  // 用来摆放位置

            nCurrentReadyIndex : {
                default : 0,
                visible : false
            }, // 用来处理放置逻辑

            bWaitingTakeAGroup : {
                default : false,
                visible : false
            },

            nTakeGroupPlayerIndex : {
                default : 0,
                visible : false
            }, // 即将要拿牌的玩家序号

            bSecondHalf : {
            	default : false,
            	visible : false
            }, // 是否为下半场

            m_pMaskLayer : {
                default : null,
                visible : false
            },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad : function () 
    {
        // 屏幕适配
        var windowSize = cc.view.getVisibleSize();
        var ratio = windowSize.width / windowSize.height;
        if (ratio < 0.563)
        {
            var offset = (640 / ratio - 1136) * 0.5 * 0.7;

            var playerBoardLayoutNode = this.node.getChildByName('playerBoardLayout');
            var playerBoardLayoutWidget = playerBoardLayoutNode.getComponent(cc.Sprite).getComponent(cc.Layout).getComponent(cc.Widget);
            playerBoardLayoutWidget.top = 15 + offset;

            var maskUP = this.node.getChildByName("maskUp");
            maskUP.height += offset;
            maskUP.active = false;
            Take6Model.m_flMaskUpHeight = maskUP.height;

            var maskDown = this.node.getChildByName("maskDown");
            maskDown.height += offset;
            maskDown.active = false;
            Take6Model.m_flMaskDownHeight = maskDown.height;

            var myPlayerBoard = this.node.getChildByName("myPlayerBoard");
            myPlayerBoard.y -= offset;

            var playerIconBase = this.node.getChildByName("playerIconBase");
            playerIconBase.y -= offset;

            var playerNameLabel = this.node.getChildByName("playerNameLabel");
            playerNameLabel.y -= offset;

            this.flPlayerCardStartY -= offset;
        }

        // hide mask
        var maskUP = this.node.getChildByName("maskUp");
        maskUP.active = false;

        var maskDown = this.node.getChildByName("maskDown");
        maskDown.active = false;

        var selectGroupMask = this.node.getChildByName("selectGroupMask");
        selectGroupMask.setLocalZOrder(1);
        selectGroupMask.active = false;

        // player board
        var nPlayerCount = Take6Model.playerCount;
        var nOpponentCount = nPlayerCount - 1;
        var spaceX = 150 +  (4 - nOpponentCount) * 20;

        var playerBoardLayoutNode = this.node.getChildByName("playerBoardLayout");
        var playerBoardLayout = playerBoardLayoutNode.getComponent(cc.Layout);

        var flPaddingLeft = (playerBoardLayoutNode.getContentSize().width - (nOpponentCount - 1) * spaceX) * 0.5;
        playerBoardLayout.paddingLeft = flPaddingLeft;
        playerBoardLayout.spacingX = spaceX;

        var myPlayerIndex = Take6Model.myPlayerIndex;
        var myPlayerBoardInfo = this.node.getChildByName('myPlayerBoard').getComponent('PlayerBoard');
        var myMaxScore = Take6Model.m_rgPlayersInfo[myPlayerIndex].nPlayerScore;
        myPlayerBoardInfo.setPlayerScore(myMaxScore);

        var playerIconBaseNode = this.node.getChildByName('playerIconBase');
        var playerIconImageNode = playerIconBaseNode.getChildByName('iconImage');
        // playerIconImageNode.setScale(0.49);
        // playerIconImageNode.setPosition(cc.p(0, -0.5));
        var iconScripte = playerIconImageNode.getComponent('IconImageScripte');
        iconScripte.setIcon(Take6Model.getPlayerIconIndex());

        var playerNameLabel = this.node.getChildByName('playerNameLabel').getComponent(cc.Label);
        playerNameLabel.string = Take6Model.getPlayerName();

        for (var i = 0; i < nOpponentCount; i++)
        {
            var newPlayerBoard = cc.instantiate(this.playerBoard);
            playerBoardLayoutNode.addChild(newPlayerBoard);
            
            var playerBoardInfo = newPlayerBoard.getComponent('PlayerBoard');
            var playerIndex = (i < myPlayerIndex ? i : i + 1);

            playerBoardInfo.setPlayerScore(Take6Model.m_rgPlayersInfo[playerIndex].nPlayerScore);
            playerBoardInfo.setPlayerName(Take6Model.m_rgPlayersInfo[playerIndex].strPlayerName);
            playerBoardInfo.setPlayerIcon(Take6Model.m_rgPlayersInfo[playerIndex].nPlayerIcon);

            this.rgPlayerBoards.push(newPlayerBoard);
        }

        // public cards
        var flDistanceX = 150;
        var flStartX = flDistanceX / 2 * -3;
        var flStartY = this.flPulicCardPositionY;

        for (var i = 0; i < 4; i++)
        {
            var cardGroup = [];
            var nIndexInGroup = 0;
            var newCardNum = 0;
            var nHeadCardNum = 0;
            var flPositionX = 0;

            do
            {
                newCardNum = Take6Model.getPublicCardNum(i, nIndexInGroup);

                if (newCardNum > 0)
                {
                    nHeadCardNum = newCardNum;

                    var newCard = cc.instantiate(this.randomCard);
                    newCard.setPosition(flStartX + i * flDistanceX, flStartY - 40 * nIndexInGroup);
                    newCard.setLocalZOrder(1);
                    this.node.addChild(newCard);

                    flPositionX = newCard.x;
            
                    var cardInfo = newCard.getComponent("cardNode");
                    cardInfo.setCardNum(newCardNum);

                    cardGroup.push(newCard);
                    nIndexInGroup++;
                }
            } while (newCardNum > 0)

            this.cardPositionsX.push(flPositionX);
            this.cardGroups.push(cardGroup);

            this.cardGroupHeadNum.push(parseInt(nHeadCardNum));
        }

        // tip arrows

        for (var i = 0; i < 4; i++)
        {
            var arrow = cc.instantiate(this.tipArrow);
            arrow.setPosition(this.cardPositionsX[i], flStartY + 110);
            arrow.active = false;
            var arrowScript = arrow.getComponent("ArrowScript");
            arrowScript.setIndex(i);
            this.node.addChild(arrow, 10);

            this.rgTipArrows.push(arrow);
        }

        // ready cards
        cc.log("readyCardOffsetX : ", this.readyCardOffsetX);
        var middleIndex = (Take6Model.playerCount - 1) * 0.5;
        for (var i = 0; i < Take6Model.playerCount; i++)
        {
            this.readyCardPositionX.push((i - middleIndex) * this.readyCardOffsetX);
        }

        // player cards
        this.showPlayerCards(false);

        // EVENTs
        this.node.on('event_player_moving_cards', function (event)
        {
            var maskUP = this.node.getChildByName("maskUp");
            maskUP.active = true;
    
            var maskDown = this.node.getChildByName("maskDown");
            maskDown.active = true;
        }, this);

        this.node.on('event_player_select_a_card', function (event)
        {
            var nPlayerIndex = event.detail.nPlayerIndex;
            var nCardNum = event.detail.nCardNum;

            var bIsAI = event.detail.bIsAI;
            var bIsTemp = event.detail.bIsTemp;

            this.onPlayerSelectCard(nPlayerIndex, nCardNum);
            this.checkPlayerIsOffline(nPlayerIndex, bIsTemp);

        }, this);

        this.node.on('event_player_cards_reorder', function (event)
        {
            this.orderPlayerCards();
        }, this);

        this.node.on('event_player_select_a_group', function (event) 
        {
        	this.endTakeGroupCountDownProgress();

            var nSelectGroup = event.detail.nTakeGroup;
            for (var i = 0; i < this.rgTipArrows.length; i++)
            {
                if (this.rgTipArrows[i].getComponent("ArrowScript").bSelected == true)
                {
                    nSelectGroup = i;
                }
                this.rgTipArrows[i].active = false;
            }

            var nActionPlayer = event.detail.nPlayerIndex;

            var bIsAI = event.detail.bIsAI;
            var bIsTemp = event.detail.bIsTemp;

            this.takeGroupCardAction(nSelectGroup, nActionPlayer, this.rgReadyCards[this.nCurrentReadyIndex - 1]);
            this.checkPlayerIsOffline(nActionPlayer, bIsTemp, true);
            
        }, this);

        this.node.on('event_sending_message_to_server', function (event)
        {
          var maskLayer = cc.instantiate(this.maskLayer);
          this.m_maskLayer = maskLayer;

          var maskLayerScript = maskLayer.getComponent('MaskScript');
          maskLayerScript.showWaitingLabel();

          this.node.addChild(maskLayer, 999);
        }, this);

        this.node.on('event_web_onmessage', function (event)
        {
          if (this.m_maskLayer != null)
          {
            this.m_maskLayer.removeFromParent();
            this.m_maskLayer = null;
          }
        }, this);

        this.node.on('event_web_onerror', function (event)
        {
          if (this.m_maskLayer != null)
          {
            var maskLayerScript = this.m_maskLayer.getComponent('MaskScript');
            maskLayerScript.showWaitingLabel("服务器错误...");
          }
        }, this);

        this.node.on('event_web_onclose', function (event)
        {
          if (this.m_maskLayer != null)
          {
            var maskLayerScript = this.m_maskLayer.getComponent('MaskScript');
            maskLayerScript.showWaitingLabel("服务器关闭...");
          }
        }, this);

        this.node.on('event_exit_room_success', function (event)
        {
            cc.director.loadScene("StartLayer");
        }, this);

        this.node.on('event_game_off_line', function (event)
        {
            cc.director.loadScene("StartLayer");
        }, this);

        this.node.on('event_end_player_progress', function (event)
        {
            var playerIconBaseNode = this.node.getChildByName('playerIconBase');
            var playerIconScripte = playerIconBaseNode.getComponent('PlayerIconScript');
            playerIconScripte.endProgress();

        }, this);

        this.startPlayerProgress();
        
        if (Take6Model.m_bContinuedGame == true)
        {
            var bHasTakeGroupCard = false;

            if (Take6Model.m_rgTakingGroupInfo.playerIndex && Take6Model.m_rgTakingGroupInfo.cardSend)
            {
                bHasTakeGroupCard = true;
                var nReadyPlayerIndex = Take6Model.m_rgTakingGroupInfo.playerIndex;
                var nReadyCardNum = Take6Model.m_rgTakingGroupInfo.cardSend;

                var selectedCard = cc.instantiate(this.randomCard);
                selectedCard.setPosition(this.getCurrentReadyPosition());
                selectedCard.scale = this.readyCardScale;
                selectedCard.setLocalZOrder(11);
                this.node.addChild(selectedCard);

                var cardInfo = selectedCard.getComponent("cardNode");
                cardInfo.setCardNum(nReadyCardNum);
                cardInfo.setPlayerIndex(nReadyPlayerIndex);
                cardInfo.setWithMask();
                cardInfo.hideCardMask(0);

                this.rgReadyCards.push(selectedCard);
            }

            // readyCards
            for (var i = 0; i < Take6Model.m_rgReadyCardsInfo.length; i++)
            { 
                var readyCardDic = Take6Model.m_rgReadyCardsInfo[i];
                var nReadyPlayerIndex = readyCardDic.playerIndex;
                var nReadyCardNum = readyCardDic.cardSend;

                var selectedCard = cc.instantiate(this.randomCard);
                selectedCard.setPosition(this.getCurrentReadyPosition());
                selectedCard.scale = this.readyCardScale;
                selectedCard.setLocalZOrder(11);
                this.node.addChild(selectedCard);

                var cardInfo = selectedCard.getComponent("cardNode");
                cardInfo.setCardNum(nReadyCardNum);
                cardInfo.setPlayerIndex(nReadyPlayerIndex);
                cardInfo.setWithMask();
                if (bHasTakeGroupCard == true)
                {
                    cardInfo.hideCardMask(0);
                }

                this.rgReadyCards.push(selectedCard);
            } 

            if (bHasTakeGroupCard == true)
            {
                this.nCurrentReadyIndex = Take6Model.playerCount - this.rgReadyCards.length + 1;
                this.waitTakeGroupCardAction();
            }
            else
            {
                this.nCurrentReadyIndex = 0;
            }

            cc.log("this.nCurrentReadyIndex : ", this.nCurrentReadyIndex);

            Take6Model.m_bContinuedGame = false;
        }

        Take6Model.m_bGameLayerOpened = true;
        Take6Model.tryToParseWaitingGamePlayMessageJson();
    },

    takeGroup : function(nGroupIndex)
    {
        var selectGroupMask = this.node.getChildByName("selectGroupMask");
        selectGroupMask.active = false;

        for (var i = this.nCurrentReadyIndex; i < this.rgReadyCards.length; i++)
        {
            this.rgReadyCards[i].setLocalZOrder(10);
            cc.log("rgReadyCards%d's Zorder is 10 at takeGroup", i);
        }

        var flDt = 0;
        var cardGroup = this.cardGroups[nGroupIndex];
        var hitPlayerPos = cc.p(-100, -200);

        if (this.nTakeGroupPlayerIndex != Take6Model.myPlayerIndex)
        {
            var playerBoardIndex = Take6Model.playerIndex2playerBoardIndex(this.nTakeGroupPlayerIndex);
            var worlPos = this.rgPlayerBoards[playerBoardIndex].convertToWorldSpace(cc.p(0, 0));
            var nodePos = this.node.convertToNodeSpaceAR(worlPos);

            hitPlayerPos = nodePos;
        }

        var nPunchCount = 0;
        var punchShowUpPos;

        if (cardGroup.length >= 1)
        {
            punchShowUpPos = cardGroup[0].position;
        }

        for (var i = 0; i < cardGroup.length; i++)
        {
            var card = cardGroup[i];
    
            var cardInfo = card.getComponent("cardNode");
            nPunchCount += cardInfo.nPunchCount;

            var actionFadeOut = cc.fadeOut(0.3);
            var actionUnion = cc.sequence(actionFadeOut, cc.removeSelf());

            card.runAction(actionUnion);

            if (i > cardGroup.length / 2 && i < cardGroup.length / 2)
            {
                punchShowUpPos = card.position;
            }
        }
        cardGroup.length = 0;
        flDt = this.hitPlayerAnimation(this.nTakeGroupPlayerIndex, nPunchCount, punchShowUpPos);

        return flDt;
    },

    gotoGroup : function(nGroupIndex, newCard, newCardNum)
    {
        var cardGroup = this.cardGroups[nGroupIndex];
        var targetPosX = this.cardPositionsX[nGroupIndex];
        var targetPosY = this.flPulicCardPositionY - 40 * this.cardGroups[nGroupIndex].length;

        var action1 = cc.delayTime(0.4 * this.flGotoGroupDuring);
        var action2 = cc.moveTo(0.6 * this.flGotoGroupDuring, targetPosX, targetPosY);
        var action3 = cc.scaleTo(0.5 * this.flGotoGroupDuring, 1.0);
        var funChangeZorder = function(target, [cardNode, nZorder])
        {
            cardNode.setLocalZOrder(nZorder);
        };

        var actionUnion = cc.sequence(action1, cc.spawn(action3, action2), cc.callFunc(funChangeZorder, this, [newCard, cardGroup.length + 1]));

        var cardInfo = newCard.getComponent("cardNode");
        cardInfo.hideTopNameBoard();

        cardGroup.push(newCard);
        this.cardGroupHeadNum[nGroupIndex] = newCardNum;
        newCard.runAction(actionUnion);

        return actionUnion.getDuration();
    },

    orderPlayerCards : function()
    {
        var flPlayerCardOffset = 45;
        if (this.rgPlayerCards.length > 12)
        {
        	flPlayerCardOffset -= (this.rgPlayerCards.length - 10) * 2;
        }

        var flPlayerCardStartY = this.flPlayerCardStartY;

        var flMidIndex = (this.rgPlayerCards.length - 1) * 0.5;

        this.rgPlayerCards.sort(this.sortCard);

        for (var i = 0; i < this.rgPlayerCards.length; i++)
        {
            this.rgPlayerCards[i].setLocalZOrder(i);
            this.rgPlayerCards[i].setPosition((i - flMidIndex) * flPlayerCardOffset, flPlayerCardStartY);
            this.rgPlayerCards[i].setLocalZOrder(0);
        } 

        var maskUP = this.node.getChildByName("maskUp");
        maskUP.active = false;

        var maskDown = this.node.getChildByName("maskDown");
        maskDown.active = false;
    },

    onPlayerSelectCard : function(nPlayerIndex, nCardNum)
    {
        var selectedCard = null;

        var flDt = 0.4;
        cc.log("Player%d send a card", nPlayerIndex);

        if (nPlayerIndex == Take6Model.myPlayerIndex)
        {
            var nSelectIndex = -1;
            for (var i = 0; i < this.rgPlayerCards.length; i++)
            {
                var card = this.rgPlayerCards[i];
                var cardInfo = card.getComponent("cardNode");

                if (cardInfo.bSelected == true)
                {
                    nSelectIndex = i;
                }
            }

            var nSelectIndex = parseInt(nSelectIndex);
            selectedCard = this.rgPlayerCards.splice(nSelectIndex, 1)[0];
    
            this.orderPlayerCards();
        }
        else
        {
            var playerBoardIndex = Take6Model.playerIndex2playerBoardIndex(nPlayerIndex);
            var worlPos = this.rgPlayerBoards[playerBoardIndex].convertToWorldSpace(cc.p(0, 0));
            var nodePos = this.node.convertToNodeSpaceAR(worlPos);

            selectedCard = cc.instantiate(this.randomCard);
            selectedCard.setPosition(nodePos);
            this.node.addChild(selectedCard);

            var cardInfo = selectedCard.getComponent("cardNode");
            cardInfo.setCardNum(nCardNum);
            cardInfo.setPlayerIndex(nPlayerIndex);
            cardInfo.setWithMask();

            flDt = 0.8;
            Take6Model.tryToParseWaitingGamePlayMessageJson();
        }

        if (selectedCard != null)
        {
            selectedCard.setLocalZOrder(11);
            cc.log("selectedCard order 11");
            this.rgReadyCards.push(selectedCard);

            selectedCard.runAction(cc.spawn(cc.scaleTo(flDt, this.readyCardScale), cc.moveTo(flDt, this.getCurrentReadyPosition())));

            if (this.rgReadyCards.length == Take6Model.playerCount)
            {
                var fun = function()
                {
                    this.clearPlayerBoardProgress();
                    this.showAllReadyCards();
                };

                this.node.runAction(cc.sequence(cc.delayTime(flDt + 0.3), cc.callFunc(fun, this)));
            }
        }
    },

    clearPlayerBoardProgress : function()
    {
        for(var i = 0; i < Take6Model.playerCount; i++)
        {
            if (Take6Model.myPlayerIndex == i)
            {
                var playerIconBaseNode = this.node.getChildByName('playerIconBase');
                var playerIconScripte = playerIconBaseNode.getComponent('PlayerIconScript');
                playerIconScripte.clearProgress();
            }
            else
            {
                var boardIndex = Take6Model.playerIndex2playerBoardIndex(i);

                var playerBoard = this.rgPlayerBoards[boardIndex];
                var playerBoardScripte = playerBoard.getComponent('PlayerBoard');
                playerBoardScripte.clearProgress();
            }
        }
    },

    getCurrentReadyPosition : function()
    {
        if (this.nCurrentReadyPositionIndex == this.readyCardPositionX.length)
        {
            this.nCurrentReadyPositionIndex = 0;
        }

        return cc.p(this.readyCardPositionX[this.nCurrentReadyPositionIndex++], this.readyCardPositionY);
    },

    sortCard : function (card1, card2) 
    {
        var card1Info = card1.getComponent("cardNode");
        var card2Info = card2.getComponent("cardNode");

        var card1Num = card1Info.nCardNum;
        var card2Num = card2Info.nCardNum;

        if (card1Num > card2Num) return 1
        else if (card1Num < card2Num) return -1
        else return 0
    },

    showAllReadyCards : function()
    {
        this.nCurrentReadyPositionIndex = 0;
        this.rgReadyCards.sort(this.sortCard);

        var flDtSum = 0;
        for (var i = 0; i < this.rgReadyCards.length; i++)
        {
            var cardInfo = this.rgReadyCards[i].getComponent("cardNode");
            var flDt = cardInfo.hideCardMask(i * 0.2);

            flDtSum = Math.max(flDt, flDtSum);
        }

        this.nextCardAction(flDtSum);
    },

    nextCardAction : function(flDelay)
    {
        if (Take6Model.playerCount != this.rgReadyCards.length)
        {
            return;
        }

        // 最后一张卡
        if (this.nCurrentReadyIndex == Take6Model.playerCount)
        {
            var funNextRound = cc.callFunc(function(target)
            {
            	this.nCurrentReadyIndex = 0;
	            this.rgReadyCards = [];
	            Take6Model.m_nCurrentRound++;
	            Take6Model.m_bReadyToTakeGroup = false;

	            if (this.rgPlayerCards.length > 0)
	            {
                    this.startPlayerProgress();

	            	cc.log("tryToParseWaitingGamePlayMessageJson");
	            	Take6Model.tryToParseWaitingGamePlayMessageJson();
	            }
	            else
	            {
	            	if (this.bSecondHalf == true) // 游戏结束 
	            	{
                        this.showResultBoard();
	            	}
	            	else
	            	{
	            		this.startPlayerProgress();
	            		this.showPlayerCards(true);
	            	}
	            }

                Take6Model.m_bInSendCardPhase = true;

            }, this);

            this.node.runAction(cc.sequence(cc.delayTime(flDelay), funNextRound));
            return;
        }

        var fun = cc.callFunc(function(target, actionCard) 
        {
            this.cardAction(actionCard);

        }, this, this.rgReadyCards[this.nCurrentReadyIndex]);

        this.node.runAction(cc.sequence(cc.delayTime(flDelay), fun));
        this.nCurrentReadyIndex++;
    },

    waitTakeGroupCardAction : function()
    {
        this.bWaitingTakeAGroup = true;

        var selectGroupMask = this.node.getChildByName("selectGroupMask");
        selectGroupMask.active = true;

        var bIsMyCard = false;

        cc.log("Current Reday Index , ", this.nCurrentReadyIndex);
        for (var i = 0; i < this.rgReadyCards.length; i++)
        {
            if (i != this.nCurrentReadyIndex - 1)
            {
                this.rgReadyCards[i].setLocalZOrder(0);
            }
            else
            {
                var readyCard = this.rgReadyCards[i];
                var readyCardInfo = readyCard.getComponent("cardNode");
                this.nTakeGroupPlayerIndex = readyCardInfo.nPlayerIndex;
                cc.log("Take group player index is : ", this.nTakeGroupPlayerIndex);

                bIsMyCard = (this.nTakeGroupPlayerIndex == Take6Model.myPlayerIndex);
            }
        }

        var selectGroupLabel = selectGroupMask.getChildByName('selectGroupLabel').getComponent(cc.Label);
        if (bIsMyCard)
        {
            selectGroupLabel.string = "请选择拿取牌组";
            this.startTakeGroupCountDownProgress();
        }
        else
        {
            selectGroupLabel.string = "等待玩家 " + Take6Model.m_rgPlayersInfo[this.nTakeGroupPlayerIndex].strPlayerName + " 选取牌组";
        }

        for (var i = 0; i < this.rgTipArrows.length; i++)
        {
            this.rgTipArrows[i].active = true;

            var cardGroup = this.cardGroups[i];
            var nGroupScore = 0;
            for (var j = 0; j < cardGroup.length; j++)
            {
                var card = cardGroup[j];
                var cardInfo = card.getComponent("cardNode");
                nGroupScore += cardInfo.nPunchCount;
            }

            var arrowScript = this.rgTipArrows[i].getComponent("ArrowScript");
            arrowScript.setScore(nGroupScore, bIsMyCard);
        }

        Take6Model.m_bReadyToTakeGroup = true;
        Take6Model.tryToParseWaitingTakeGroupMessageJson();
    },

    // 需要等待玩家操作的拿牌操作
    takeGroupCardAction : function(nTakeGroupIndex, nPlayerIndex, actionCard)
    {
        var flDelay = this.takeGroup(nTakeGroupIndex);
        var nCardNum = actionCard.getComponent("cardNode").nCardNum;
        this.gotoGroup(nTakeGroupIndex, actionCard, nCardNum);
        flDelay = Math.max(flDelay, this.flGotoGroupDuring);

        // var fun = cc.callFunc(function(target, [nTakeGroupIndex, actionCard, nCardNum]) 
        // {
        //     this.gotoGroup(nTakeGroupIndex, actionCard, nCardNum);
        // }, this, [nTakeGroupIndex, actionCard, nCardNum]);

        // this.node.runAction(cc.sequence(cc.delayTime(flDelay), fun));

        this.nextCardAction(flDelay);
        this.bWaitingTakeAGroup = false;
    },

    cardAction : function(actionCard)
    {
        var cardInfo = actionCard.getComponent("cardNode");
        var nCardNum = cardInfo.nCardNum;
        var nGroup = 4;

        // case1 : new card is smallest of all the heads
        var bNewCardSmallest = true;
        for (var i = 0; i < nGroup; i++)
        {
            if (this.cardGroupHeadNum[i] < nCardNum)
            {
                bNewCardSmallest = false;
            }
        }

        if (bNewCardSmallest == true)
        {
            this.waitTakeGroupCardAction();
            return;
        }

        // case2 : new card is bigger then some of the heads

        var maxSmallerNum = 0;
        var nGroupIndex = -1;
        for (var i = 0; i < nGroup; i++)
        {
            if (this.cardGroupHeadNum[i] < nCardNum && this.cardGroupHeadNum[i] > maxSmallerNum)
            {
                maxSmallerNum = this.cardGroupHeadNum[i];
                nGroupIndex = i;
            }
        }

        if (nGroupIndex >= 0)
        {
            if (this.cardGroups[nGroupIndex].length < 5)
            {
                var flGotoGroupDt = this.gotoGroup(nGroupIndex, actionCard, nCardNum);
                this.nextCardAction(flGotoGroupDt);
            }
            else
            {
                this.nTakeGroupPlayerIndex = cardInfo.nPlayerIndex;
                var flTakeGroupDt = this.takeGroup(nGroupIndex);
                var flGotoGroupDt = this.gotoGroup(nGroupIndex, actionCard, nCardNum);
                this.nextCardAction(Math.max(flTakeGroupDt, flGotoGroupDt));
            }
        }
    },

    // TEST 模拟其他玩家打出一张牌
    opponentSendACard : function()
    {
        if (TestPlayerIndex == 4)
        {
            TestPlayerIndex = 0;
        }

        Take6Model.getAServerCard(TestPlayerIndex, Take6Model.getACard());
        TestPlayerIndex++;
    },

    hitPlayerAnimation : function(nPlayerIndex, nHitCount, startPos) //nPunchCount
    {
        // var nPlayerIndex = 0;
        // var nHitCount = 10;
        // var startPos = cc.p(0, 0);
        var flDt = 0;
        var hitNodePos;

        var cardToPunchPartical = cc.instantiate(this.cardToPunch);
        cardToPunchPartical.setPosition(startPos);     
        this.node.addChild(cardToPunchPartical, 20);

        var flDelayBase = 0.2;
        var flDelay = flDelayBase;
        for (var i = 0; i < nHitCount; i++)
        {
            var bLeftOrRight = Math.random();

            if (nPlayerIndex != Take6Model.myPlayerIndex)
            {
                var hitWorldPos = this.rgPlayerBoards[Take6Model.playerIndex2playerBoardIndex(nPlayerIndex)].convertToWorldSpace(cc.p(0, 0));
                hitNodePos = this.node.convertToNodeSpaceAR(hitWorldPos);
            }
            else
            {
                var playerIconBaseNode = this.node.getChildByName('playerIconBase');
                hitNodePos = playerIconBaseNode.position;
            }

            var flHitRandomX = (Math.random() - 0.5) * 20;
            var flHitRandomY = (Math.random() - 0.5) * 20;
            hitNodePos = cc.p(hitNodePos.x + flHitRandomX, hitNodePos.y + flHitRandomY);

            var flStartRandomX = (bLeftOrRight > 0.5) ? 30 + Math.random() * 60 : -20 + Math.random() * -60;
            var flStartRandomY = (Math.random() - 0.5) * 70;
            var startPosRandom = cc.p(startPos.x + flStartRandomX, startPos.y + flStartRandomY);

            var punchNode = new cc.Node();
            var PunchSprite = punchNode.addComponent(cc.Sprite);
            PunchSprite.spriteFrame = this.punchFrame;

            punchNode.opacity = 0;
            punchNode.setPosition(startPos);
            this.node.addChild(punchNode, 10);

            // Action1 JumpOut
            var actionOut = cc.fadeIn(0.3);
            var actionJump = cc.jumpTo(0.5, startPosRandom, 20, 2);
            var actionJumpOut = cc.spawn(actionOut, actionJump);

            // Action2 Delay
            var actionDelay = cc.delayTime(flDelay);
            flDelayBase = flDelayBase * 0.9;
            flDelay += flDelayBase;

            // Action3 BezierMove
            var randomX1 = Math.random() * 50 + 100;
            if (bLeftOrRight < 0.5)
            {
                randomX1 = randomX1 * -1;
                punchNode.runAction(cc.flipX(true));
            }
            var config1X = startPos.x + randomX1;
            var config2X = hitNodePos.x + randomX1;
            var config1Y = startPos.y + (hitNodePos.y - startPos.y) / 3;
            var config2Y = hitNodePos.y - (hitNodePos.y - startPos.y) / 3

            var bezierConfig = [cc.p(config1X, config1Y), cc.p(config2X, config2Y), hitNodePos];
            var dt = 0.4 + 0.2 * Math.random();
            var actionPunchMove = cc.punchAction(dt, bezierConfig);

            // Action4 Hit
            var funHitParticle = function(target, pos)
            {
                var punchSpark = cc.instantiate(this.punchSpark);
                punchSpark.setScale(0.3 + 0.2 * Math.random());
                punchSpark.setPosition(pos);     
                this.node.addChild(punchSpark, 9);                
            };
            var actionSparcle = cc.callFunc(funHitParticle, this, hitNodePos);

            // Action5 Change Score
            var funChangeScore = function(target, nPlayerIndex)
            {
                var playerBoardInfo;
                if (nPlayerIndex == Take6Model.myPlayerIndex)
                {
                    playerBoardInfo = this.node.getChildByName('myPlayerBoard').getComponent('PlayerBoard');
                }
                else
                {
                    var nPlayerBoardIndex = Take6Model.playerIndex2playerBoardIndex(nPlayerIndex);
                    playerBoardInfo = this.rgPlayerBoards[nPlayerBoardIndex].getComponent('PlayerBoard');
                }
                playerBoardInfo.setPlayerScore(playerBoardInfo.m_nPlayerScore - 1);
                Take6Model.m_rgPlayersInfo[nPlayerIndex].nPlayerScore = playerBoardInfo.m_nPlayerScore - 1;
            };
            var actionChangeScore = cc.callFunc(funChangeScore, this, nPlayerIndex);

            var actionUnion = cc.sequence(actionJumpOut, actionDelay, actionPunchMove, actionSparcle, actionChangeScore, cc.fadeOut(0.3), cc.removeSelf());
            flDt = Math.max(flDt, actionUnion.getDuration());
            punchNode.runAction(actionUnion);
        }

        return flDt;
    },

    showPlayerCards : function (bSecondHalf)
    {
        var nSecondHalfOffset = 0;

        if (bSecondHalf == true)
        {
            this.bSecondHalf = true;
            nSecondHalfOffset = Take6Model.cardCount;
        }
        
    	for (var i = 0; i < Take6Model.cardCount; i++)
        {
            var newCard = cc.instantiate(this.randomCard);
            this.node.addChild(newCard);

            var cardInfo = newCard.getComponent("cardNode");
            cc.log("get card %d", i + nSecondHalfOffset);
            cardInfo.setCardNum(Take6Model.getPlayerCardNum(i + nSecondHalfOffset));
            cardInfo.setPlayerIndex(Take6Model.myPlayerIndex);
            cardInfo.bCanBeTouched = true;

            this.rgPlayerCards.push(newCard);
        }
        this.orderPlayerCards();

        if (bSecondHalf == true)
        {
            // 如果有发牌动画 在发牌动画之后执行
            Take6Model.tryToParseWaitingGamePlayMessageJson();
        }
    },

    showResultBoard : function ()
    {
        var resultBoard = cc.instantiate(this.resultBoard);
        this.node.addChild(resultBoard, 100);
    },

    checkPlayerIsOffline : function (nPlayerIndex, bIsTemp, bIsTakeGroup)
    {
        if (Take6Model.myPlayerIndex == nPlayerIndex)
        {
            var playerIconBaseNode = this.node.getChildByName('playerIconBase');
            var playerIconScripte = playerIconBaseNode.getComponent('PlayerIconScript');

            if (bIsTakeGroup == true)
            {
            	playerIconScripte.clearProgress();
            }
            else
            {
            	playerIconScripte.endProgress();
            }

            return;
        }

        if (Take6Model.myPlayerIndex < nPlayerIndex)
        {
            nPlayerIndex -= 1;
        }

        var playerBoard = this.rgPlayerBoards[nPlayerIndex];
        var playerBoardScripte = playerBoard.getComponent('PlayerBoard');
        playerBoardScripte.setOffline(bIsTemp);
        if (bIsTakeGroup == true)
        {
        	playerBoardScripte.clearProgress();
        }
        else
        {
        	playerBoardScripte.endProgress();
        }
    },

    startPlayerProgress : function ()
    {
        var nPlayerCount = Take6Model.playerCount;

        for (var i = 0; i < nPlayerCount; i++)
        {
            if (Take6Model.myPlayerIndex == i)
            {
                var playerIconBaseNode = this.node.getChildByName('playerIconBase');
                var playerIconScripte = playerIconBaseNode.getComponent('PlayerIconScript');
                playerIconScripte.startProgress(this.selfSendCardCountDownCallBack, this.rgPlayerCards);
            }
            else
            {
                var nOtherPlayerIndex = i;
                if (Take6Model.myPlayerIndex < i)
                {
                    nOtherPlayerIndex--;
                }

                var playerBoard = this.rgPlayerBoards[nOtherPlayerIndex];
                var playerBoardScripte = playerBoard.getComponent('PlayerBoard');
                playerBoardScripte.startProgress(this.opponentSendCardCountDownCallBack, i);
            }
        }
    },

    selfSendCardCountDownCallBack : function (rgCards)
    {
        var nCardCount = rgCards.length;
        var nRandomCardIndex = parseInt(Math.random() * nCardCount);

        cc.log("selectedCard index is : %d", nRandomCardIndex);

        var selectedCard = rgCards[nRandomCardIndex];
        var cardInfo = selectedCard.getComponent("cardNode");
        var nCardNum = cardInfo.nCardNum;
        cardInfo.showCardMask();
        cardInfo.bSelected = true;

        Take6Model.playerSendCardToServer(nCardNum);
    },

    opponentSendCardCountDownCallBack : function (nPlayerIndex)
    {
        Take6Model.kickOpponentOutRequest(nPlayerIndex);
    },

    startTakeGroupCountDownProgress : function ()
    {
        this.m_nTakeGorupLeftTime = Take6Model.m_nWaitSendCardTime;
        this.takeGroupCountDownCallBack();
        this.schedule(this.takeGroupCountDownCallBack, 1);
    },

    endTakeGroupCountDownProgress : function ()
    {
    	var selectGroupMask = this.node.getChildByName("selectGroupMask");
    	var countDownLabelNode = selectGroupMask.getChildByName('countDownLabel');

    	this.unschedule(this.takeGroupCountDownCallBack);
    	countDownLabelNode.active = false;
        this.m_nTakeGorupLeftTime = Take6Model.m_nWaitSendCardTime;
    },

    takeGroupCountDownCallBack : function ()
    {
    	var selectGroupMask = this.node.getChildByName("selectGroupMask");
    	var countDownLabelNode = selectGroupMask.getChildByName('countDownLabel');

        if (this.m_nTakeGorupLeftTime > 0)
        {
        	countDownLabelNode.active = true;
        	var countDownLabel = countDownLabelNode.getComponent(cc.Label);
        	countDownLabel.string = "剩余时间:";

            var node = new cc.Node("label");
            if (this.m_nTakeGorupLeftTime < 10)
            {
				node.scale = 1.3;
				node.oppacity = 100;
            }
            else
            {
            	node.scale = 0.7;
            	node.oppacity = 255;
            }
            
            node.setLocalZOrder(10);
            var nodePosition = cc.v2(countDownLabelNode.x + 20, countDownLabelNode.y);
            node.setPosition(nodePosition);

            var action1 = cc.fadeIn(0.3);
            var action2 = cc.delayTime(0.2);
            var action3 = cc.fadeOut(0.3);
            var action4 = cc.scaleTo(0.3, 0.7);
            var action5 = cc.removeSelf();

            var actionUnion1 = cc.spawn(action4, cc.sequence(action1, action2, action3, action5));

            var label = node.addComponent(cc.Label);
            label.string = this.m_nTakeGorupLeftTime.toString()

            node.runAction(actionUnion1);

            node.parent = selectGroupMask;
            this.m_nTakeGorupLeftTime--;
        }
        else
        {
        	countDownLabelNode.active = false;
            this.m_nTakeGorupLeftTime = Take6Model.m_nWaitSendCardTime;
            this.unschedule(this.takeGroupCountDownCallBack);

            var randomGroup = parseInt(Math.random() * 5);
            Take6Model.playerTakeGroupToServer(randomGroup);
        }
    },

    // start : function () 
    // {
    // },

    // update (dt) {},
});
